//
//  AppDelegate.m
//  EducationAdminClient
//
//  Created by kwsdzjx on 15/11/25.
//  Copyright © 2015年 周佳兴. All rights reserved.
//

/**
 Description: Some User Type
 One:   老师端：UserType = @"Teacher";
 Two:   学员端：UserType = @"Student";
 Three: 其他端：UserType = @"Other";asdfasdfasdfasdfasdfasdfasdfasdfasdf
 */
#pragma mark  事务看板版本客户化
#pragma mark

#import "AppDelegate.h"
//#import "APService.h"asdfasdf
#import "LoginViewController.h"

#import "CustomTabbarViewController.h"
#import "leftViewController.h"
#import "JPUSHService.h"
#import "ProjectChooseViewController.h"
#import "DetailViewController.h"
#import "ProjectModel.h"
#import <Bugly/Bugly.h>
#import "TimeOverViewController.h"
#import "WelcomeViewController.h"
#import <PgyUpdate/PgyUpdateManager.h>

@interface AppDelegate (){
    NSMutableArray *dataArr;
    LoginViewController *lgVc;
}
@property(nonatomic,strong)UIView *timeOverView;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    dataArr =[NSMutableArray array];
    // Override point for customization after application launch.
    
    if(getBase().length<=0){
        
        saveBaseUrl(BASE_URL);
    }
    // 我我偶偶尔去哦围殴IQ为欧全文我欧趣味欧全文UI偶企鹅u
    NSString *UIStyle;
    NSString *UserType;
    // NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    //    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"ifloging"];
    lgVc = [[LoginViewController alloc]init];
    if([str isEqualToString:@"loging"]){
        self.window.rootViewController = lgVc;
    }else{
        self.window.rootViewController = lgVc;
    }
    UIStyle = @"0";//修改主题
    saveUIStyle(UIStyle);
     if ([UIStyle isEqualToString:@"0"]) {//主项目暂为教师端
        NSLog(@"这里是教师端");
        UserType = UserISHPSTeacher;
    }else if ([UIStyle isEqualToString:@"1"]){//暂时作为学员端
        NSLog(@"这里是学员端");
        UserType = UserISHPSStudent;
    }else{// 其他端
        NSLog(@"其他端");
        UserType = UserISOther;
    }
    saveUserType(UserType);
    NSLog(@"%@",getUserType());/*#define EnglishLanguage @"EnglishLanguage"//语言版本为英文
                                #define AvatarUpload @"AvatarUpload"//头像上传功能
                                #define LeftRightModel @"LeftRightModel"//左右结构功能
                                #define UserRoleName @"UserRoleName"//用户角色名是否显示
                                #define TimeLineModel @"TimeLineModel"//时间轴模块功能
                                #define EvalutionModel @"EvalutionModel"//评价模块*/
    
    
    
    //使用主项目登录UI，不使用请注释掉
    setMainLoginUI(YES);
    //这里添加了角色判断  不用改
    if ([getUserType() isEqualToString:UserISHPSTeacher]) {
        setAvatarUpload(YES);//头像上传功能
        setEnglishLanguage(NO);//语言版本为英文
        setLeftRightModel(YES);//列表页           多选项卡 内容 左右结构 YES 标题切换 NO
        setUserRoleName(YES);//用户角色名是否显示
        setTimeLineModel(YES);//时间轴模块功能
        setEvalutionModel(YES);//评价模块
        setPersonalInformationStarUI(NO);
    }else{
        setAvatarUpload(NO);//头像上传功能
        setEnglishLanguage(NO);//语言版本为英文
        setLeftRightModel(YES);//列表页           多选项卡 内容 左右结构 YES 标题切换 NO
        setUserRoleName(YES);//用户角色名是否显示
        setTimeLineModel(YES);//时间轴模块功能
        setEvalutionModel(YES);//评价模块
        setPersonalInformationStarUI(NO);
//        setAvatarUpload(NO);
//        setEnglishLanguage(NO);
//        setLeftRightModel(NO);
//        setUserRoleName(NO);
//        setTimeLineModel(NO);
//        setEvalutionModel(NO);
//        setPersonalInformationStarUI(NO);
    }

    [self.window makeKeyAndVisible];
    [JPUSHService setupWithOption:launchOptions appKey:@"b941bcd18c4aec39146fb25c" channel:@"hps_edus" apsForProduction:NO advertisingIdentifier:nil];
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    //            [Bugly startWithAppId:@"900034755"]; // 腾讯 bugly 集成
    //#ifdef Main
//    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//    [ud removeObjectForKey:@"NEEDSV"];
//    [ud synchronize];

    //NSLog(@"主项目程序");
    //ProjectChooseViewController *proVC = [[ProjectChooseViewController alloc]init];
    //self.window.rootViewController = proVC;
    [self dataRequest];
    
    
    [self notify];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    //    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    return YES;
    
    
    
    
    
}

#pragma mark - DataRequest
-(void)dataRequest{
    
    NSMutableDictionary *parama = [[NSMutableDictionary alloc]init];
    [parama setObject:@"0" forKey:@"source"];
    
    NSString *requestStr = [NSString stringWithFormat:@"%@%@", getBase(), PROJECTREQUEST_URL];
    [NetRequest requestUrl:requestStr andParamas:parama andReturnBlock:^(NSData *data, NSError *error) {
        if (!error&&data!=nil) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", string);
            //            NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            
            [self dataUes:obj];
            NSLog(@"%@", obj);
            
        }else{
            //            NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
            ////            [self showLabelWithText:str];
            
        }
    }];
}

#pragma mark - data USE
-(void)dataUes:(id)obj{
    NSArray *arr = [[NSArray alloc]initWithArray:obj];
    
    [dataArr removeAllObjects];
    
    
    
    NSString * str1 = getBase();
    NSArray *urlArr = [str1 componentsSeparatedByString:@":"];
    NSArray *usedArr = [[urlArr lastObject] componentsSeparatedByString:@"/"];
    NSString *usedStr = [usedArr firstObject];
    
    NSLog(@"%@",usedStr);
    
    NSString *usertype = @"";
    if([getUserType() isEqualToString:UserISHPSStudent]){
        usertype = @"学员端";
    }else if([getUserType() isEqualToString:UserISHPSTeacher]){
        usertype = @"主项目";
    }else{
        usertype = @"学员端";
    }
    
    for (NSDictionary *dic in arr) {
        ProjectModel *model = [[ProjectModel alloc]init];
        model = [model initWithDictionary:dic error:nil];
        if ([model.programa_url isEqualToString:@"localhost"]) {
            model.programa_url = @"192.168.6.150";
        }
        
        
        if([model.programa_name isEqualToString:@"主项目"]){
            //            model.pro_port = usedStr;
            [dataArr addObject:model];
        }
    }
//    NSString *UIStyle;
//    NSString *UserType;
//    UIStyle = getUIStyle();
//    if ([UIStyle isEqualToString:@"0"]) {//主项目暂为教师端
//        NSLog(@"这里是教师端");
//        UserType = UserISHPSTeacher;
//    }else if ([UIStyle isEqualToString:@"1"]){//暂时作为学员端
//        NSLog(@"这里是学员端");
//        UserType = UserISHPSStudent;
//    }else{// 其他端
//        NSLog(@"其他端");
//        UserType = UserISOther;
//    }
//    saveUserType(UserType);
//    NSLog(@"%@",getUserType());
    ProjectModel *model;
    if (dataArr.count>0) {
        model = dataArr[0];
    }
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:model.proId forKey:PROID];
    [userDefault setObject:model.programa_url forKey:PROGRAMA];
    [userDefault setObject:model.pro_port forKey:PORT];
    
    [userDefault synchronize];
    
    //    lgVc = [[LoginViewController alloc]init];
    lgVc.projectArr = dataArr;
    //    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    //    NSString *str = [[NSUserDefaults standardUserDefaults]objectForKey:@"ifloging"];
    //    if([str isEqualToString:@"loging"]){
    //        self.window.rootViewController = lgVc;
    //    }else{
    //        self.window.rootViewController = lgVc;
    //    }
    //    [self.window makeKeyAndVisible];
}


- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Required
    //    [APService registerDeviceToken:deviceToken];
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [JPUSHService registerDeviceToken:deviceToken];
}



- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void
                        (^)(UIBackgroundFetchResult))completionHandler {
    // IOS 7 Support Required
    NSLog(@"%@",userInfo);
    NSUserDefaults *ud1 = [NSUserDefaults standardUserDefaults];
    
    
    _badge =[[[userInfo objectForKey:@"aps"] objectForKey:@"badge"] integerValue];
    //    [APService handleRemoteNotification:userInfo];
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive){
        NSLog(@"前台");
        NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
        [pushJudge setObject:@"push"forKey:@"push"];
        //        DetailViewController *cus =[[DetailViewController alloc]init];
        NSString * mainId = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"mainId"]];
        NSString *titleName = [userInfo objectForKey:@"titleName"];
        NSString *noticeName = [userInfo objectForKey:@"notice_name"];
        NSString *createDate = [userInfo objectForKey:@"createDate"];
        
        NSLog(@"%@%@%@",titleName,noticeName,createDate);
        
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:titleName message:noticeName preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *Action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            LoginViewController *proVC = [[LoginViewController alloc]init];
            self.window.rootViewController = proVC;
            
        }];
        [alertC addAction:Action];
        [[self getCurrentVC] presentViewController:alertC animated:YES completion:^{
            
        }];
        
        
    }else{
        NSLog(@"后台");
        NSUserDefaults*pushJudge = [NSUserDefaults standardUserDefaults];
        [pushJudge setObject:@"push"forKey:@"push"];
        DetailViewController *cus =[[DetailViewController alloc]init];
        NSString * mainId = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"mainId"]];
        NSString *titleName = [userInfo objectForKey:@"titleName"];
        NSString *noticeName = [userInfo objectForKey:@"notice_name"];
        NSString *createDate = [userInfo objectForKey:@"createDate"];
        
        NSLog(@"%@%@%@",titleName,noticeName,createDate);
        
        
        
        NSLog(@"%@",mainId);
        cus.titleName = titleName;
        cus.noticeName = noticeName;
        cus.createDate = createDate;
        cus.isPush = YES;
        cus.mainId = mainId;
        //        BOOL issucess = [JPUSHService setBadge:5];
        //        [JPUSHService resetBadge];
        //        NSLog(@"%zd ",issucess);
//        _badge = _badge-1;
        [ud1 setObject:[NSString stringWithFormat:@"%zd",_badge] forKey:@"badge"];
        [ud1 synchronize];
        
        [JPUSHService setBadge:_badge];
        cus.message = userInfo;
        
        UINavigationController * Nav = [[UINavigationController alloc]initWithRootViewController:cus];//这里加导航栏是因为我跳转的页面带导航栏，如果跳转的页面不带导航，那这句话请省去。
        [cus setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
        [self.window.rootViewController presentViewController:Nav animated:YES completion:nil];
    }
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = _badge;
    //    [self.window.rootViewController presentViewController:cus animated:YES completion:nil];
    
    // IOS 7 Support Required
    
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}




-(void)notify{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(nitiAction:) name:@"login" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(relogin:) name:@"relogin" object:nil];
}


- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    //    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    //    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //自定义参数，key是自己定义的
    NSArray *arr = [extras allKeys];
    if(arr.count>0){
        NSString *str = [extras objectForKey:arr[0]];
        [[NSUserDefaults standardUserDefaults]setObject:arr[0] forKey:@"pushType"];
        [[NSUserDefaults standardUserDefaults]setObject:str forKey:@"timeStr"];
        //    NSString *beforeTime =[[NSUserDefaults
        //    [[NSUserDefaults standardUserDefaults]setObject:str forKey:arr[0]];
        
        [[NSUserDefaults standardUserDefaults]setObject:str forKey:arr[0]];
    }
    
    
}


- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

-(void)relogin:(NSNotification *)n{
    //    TimeOverViewController *tv =[[TimeOverViewController alloc]init];
    //    [self.window.rootViewController presentViewController:tv animated:YES completion:^{
    //    }];
    
    
    
    //    _timeOverView =[[UIView alloc]initWithFrame:CGRectMake(50, 200, KWIDTH-100, 200)];
    //     _timeOverView.backgroundColor =[UIColor whiteColor];
    //    _timeOverView.layer.borderWidth = 1;
    //    _timeOverView.layer.borderColor =[[UIColor colorWithHex:0x23c9ee]CGColor];
    //
    //    UILabel *la = [[UILabel alloc]initWithFrame:CGRectMake(20, 30, KWIDTH-100-40, 30)];
    //    [_timeOverView addSubview:la];
    //    la.text = @"系统超时,请点击确定重新登录";
    //    la.textAlignment = NSTextAlignmentCenter;
    //
    //    UIButton *btn = [[UIButton alloc]init];
    //    [_timeOverView addSubview:btn];
    //    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerX.equalTo(_timeOverView.mas_centerX);
    //        make.width.equalTo(@(100));
    //        make.height.equalTo(@(30));
    //        make.bottom.equalTo(_timeOverView.mas_bottom).offset(-10);
    //    }];
    //    [btn setTitle:@"确定" forState:UIControlStateNormal];
    //    [btn setTitleColor:[UIColor colorWithHex:0x23c9ee] forState:UIControlStateNormal];
    //    btn.layer.borderWidth = 1;
    //    btn.layer.borderColor =[[UIColor colorWithHex:0x23c9ee]CGColor];
    //    [btn addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchUpInside];
    

    NSString *messageStr = @"";
    NSString *OKStr = @"";
    //这里添加功能判断
    if (getEnglishLanguage()) {
        messageStr = @"System timeout, please click OK to login again";
        OKStr = @"OK";
    }else{
        messageStr = @"系统超时,请点击确定重新登录";
        OKStr = @"确定";
    }

    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"" message:messageStr preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *Action = [UIAlertAction actionWithTitle:OKStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        LoginViewController *proVC = [[LoginViewController alloc]init];
        self.window.rootViewController = proVC;
        
    }];
    [alertC addAction:Action];
    [[self getCurrentVC] presentViewController:alertC animated:YES completion:^{
        
    }];
    //    [[self getCurrentVC].view addSubview:_timeOverView];
    //    [[self getCurrentVC].view bringSubviewToFront:_timeOverView];
    
    //    LoginViewController *proVC = [[LoginViewController alloc]init];
    //    self.window.rootViewController = proVC;
}


-(void)sureClick{
    LoginViewController *proVC = [[LoginViewController alloc]init];
    self.window.rootViewController = proVC;
}

-(void)nitiAction:(NSNotification *)n{
    NSString *str = [n object];
    if([str isEqualToString:@"loginSuccees"]){
        
        
        //AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        //UIViewController* topViewController = appdelegate.rootController.navigationController.topViewController;
        
        //NSLog(@"------------------ %@ --------------------", topViewController);
        
        self.window.rootViewController = nil;
        
        //#ifdef Main
        NSLog(@"主项目程序");
        CustomTabbarViewController *fv = [[CustomTabbarViewController alloc]init];
        self.window.rootViewController = fv;
        //#elif Student
        //        NSLog(@"学员端程序");
        //        //                self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen]
        //        //                                                                bounds]];
        //        //        [self dataRequest];
        //        CustomTabbarViewController *fv = [[CustomTabbarViewController alloc]init];
        //        self.window.rootViewController = fv;
        //        //                self.window.backgroundColor = [UIColor whiteColor];
        //        [self.window makeKeyAndVisible];
        //
        //
        //#else
        //        NSLog(@"主项目程序");
        //        CustomTabbarViewController *fv = [[CustomTabbarViewController alloc]init];
        //        self.window.rootViewController = fv;
        //#endif
        
        
        
        //        MainPageViewController *mainVC = [[MainPageViewController alloc] init];
#pragma - mark 屏蔽左滑菜单
        //        leftViewController *lvc = [[leftViewController alloc] init];
        //        self.mainNavigationController = fv;
        ////        LeftSortsViewController *leftVC = [[LeftSortsViewController alloc] init];
        //        self.LeftSlideVC = [[LeftSlideViewController alloc] initWithLeftView:lvc andMainView:self.mainNavigationController];
        //        self.window.rootViewController = self.LeftSlideVC;
        
        
        //    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:fv];
        //    [nav.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav2"] forBarMetrics:UIBarMetricsDefault];
        //        self.window.rootViewController =slvc;
    }else if([str isEqualToString:@"exit"]){
        //        ProjectChooseViewController *proVC = [[ProjectChooseViewController alloc]init];
        //#ifdef Main
        NSLog(@"主项目程序");
        //        ProjectChooseViewController *proVC = [[ProjectChooseViewController alloc]init];
        //        self.window.rootViewController = proVC;
        LoginViewController *proVC = [[LoginViewController alloc]init];
        self.window.rootViewController = proVC;
        
        //#elif Student
        //        NSLog(@"学员端程序");
        //        ProjectModel *model = [[ProjectModel alloc]init];
        //        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        //        model.proId = [userDefault objectForKey:PROID];
        //        model.programa_url = [userDefault objectForKey:PROGRAMA];
        //        model.pro_port = [userDefault objectForKey:PORT];
        //        NSMutableArray *arr =[NSMutableArray array];
        //        [arr addObject:model];
        //        [userDefault setValue:@"nologing" forKey:@"ifloging"];
        //        [userDefault synchronize];
        //
        //        LoginViewController *loginVC = [[LoginViewController alloc]init];
        //        self.window.rootViewController = loginVC;
        //        loginVC.dataArr = arr[0];
        //#elif Teacher
        //        NSLog(@"老师端程序");
        //#else
        //        ProjectChooseViewController *proVC = [[ProjectChooseViewController alloc]init];
        //        self.window.rootViewController = proVC;
        //        NSLog(@"都不是");
        //#endif
        
        
        //        LoginViewController *lv = [[LoginViewController alloc]init];
        //        self.window.rootViewController =lv;
        
    }
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    //    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSLog(@"进入前台");
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSInteger badge = [[ud objectForKey:@"badge"] integerValue];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
